package com.taptech.doufu.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.media.ThumbnailUtils
import android.os.Bundle
import android.os.Environment
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.Toast
import com.taptech.doufu.R
import com.taptech.doufu.bean.ShareBeansInfo
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.constant.ShareType
import com.taptech.doufu.model.novel.bean.NovelDetailBean
import com.taptech.doufu.net.retrofit.api.RxJavaHelper
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity
import com.taptech.doufu.ui.view.WaitDialog
import com.taptech.doufu.util.*
import kotlinx.android.synthetic.main.activity_story_detail.*
import kotlinx.android.synthetic.main.activity_story_poster.*
import kotlinx.android.synthetic.main.activity_story_poster.layBack
import kotlinx.android.synthetic.main.activity_story_poster.layContent
import kotlinx.android.synthetic.main.activity_story_poster.tvContent
import kotlinx.android.synthetic.main.activity_story_poster.tvTitle
import rx.Observable
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.concurrent.TimeUnit


class StoryPosterActivity : DiaobaoBaseActivity(){
    private var waitDialog:WaitDialog? = null
    private var novelId = 0
    private var objectType = 5
    private var shareUrl = ""


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_story_poster)
        waitDialog = WaitDialog(this,R.style.updateDialog)
        waitDialog?.show()
        initView()
        val bean = intent.getSerializableExtra(Constant.DATA) as NovelDetailBean
        setData(bean)

    }


    fun initView() {

        layBack.setOnClickListener {
            finish()
        }
        layWeixin.setOnClickListener {
            share(ShareType.Weixin)
        }
        layQQ.setOnClickListener {
            share(ShareType.QQ)
        }
        layWeibo.setOnClickListener {
            share(ShareType.Weibo)
        }
        layDownload.setOnClickListener {
            download()
        }

    }


    fun setData(novel: NovelDetailBean) {
        novelId = novel.id
        shareUrl = novel.shareUrl
        objectType = novel.object_type
        ivQRCode.setImageBitmap(ZXingUtils.createQRImage(novel.shareUrl,ScreenUtil.dip2px(this,60f),ScreenUtil.dip2px(this,60f)))
        tvTitle.text = novel.title
        tvAuthor.text = novel.user.name
        tvDate.text = TimeDateFunction.toDate(novel.update_time*1000)
        val content = formatContent(novel.description)
        if (content.length>3000){
            try {
                TextUtil.setParagraphSpacing(this,tvContent,"${content.substring(0..3000)}......",14,0)
            } catch (e: Exception) {
                e.printStackTrace()
                TextUtil.setParagraphSpacing(this,tvContent,content,14,0)
            }
            tvTip.visibility = View.VISIBLE
            tvTip.text = "未完待续，上豆花APP搜小故事《${novel.title}》可免费看全部内容，还可以与作者互动！"
        }else{
            TextUtil.setParagraphSpacing(this,tvContent,content,14,0)
            tvTip.visibility = View.GONE
        }

        val tip = "由豆花APP分享"
        val spannableString = SpannableStringBuilder()
        spannableString.append(tip)
        val span = ForegroundColorSpan(Color.parseColor("#fe6e6e"))
        spannableString.setSpan(span, 1, 6, Spannable.SPAN_PRIORITY)
        tvFrom.text = spannableString
        Observable.timer(1500,TimeUnit.MILLISECONDS)
                .compose(RxJavaHelper.observeOnMainThread())
                .subscribe {
                    createPic()
                    waitDialog?.dismiss()
                }
    }

    fun formatContent(input:String):String {
        var content = input.trim()
        if (TextUtils.isEmpty(content)) {
            return ""
        }
        content = content.replace("　".toRegex(), "")
        content = content.replace(" ".toRegex(), "")
        content = content.replace(" ".toRegex(), "")
        content = content.replace("\t".toRegex(), "")
        content = content.replace("\n\n\n\n".toRegex(), "\n")
        content = content.replace("\n\n\n".toRegex(), "\n")
        content = content.replace("\n\n".toRegex(), "\n")
        content = content.replace("\r\n".toRegex(), "\n")
        return content
    }

    private fun createPic() {
        val bitmap = getViewBitmap(layContent)
        if (bitmap != null) {
            ivBigPic.setImageBitmap(bitmap)
        }
    }



    fun share(type:Int) {
        var bitmap = getViewBitmap(layContent)
        val info = ShareBeansInfo()
        info.setSocial_type(type)
        info.setShareUrl(shareUrl)
        info.object_type = "$objectType"
        info.id = "$novelId"
        if (type == ShareType.QQ|| type == ShareType.QQSpace){
            info.setDataType(Constant.ShareDataType.SHARE_DATA_TYPE_IMAGE)
            val tempPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath + "/poster.png"
            BitmapUtil.saveSDcard(bitmap, tempPath)
            info.setImagUrl(tempPath)
        }else if(type == ShareType.Weibo){
            info.setFlag(ShareBeansInfo.NOVEL_SHARE_FLAG)
            val tempPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath + "/temp_poster_${System.currentTimeMillis()}.png"
            BitmapUtil.saveSDcard(bitmap, tempPath)
            info.setImagUrl(tempPath)
        }
        bitmap = BitmapUtil.imageZoom(bitmap,450.00)
        ShareUtils.shareBigPic(this,type,bitmap,info)
    }

    fun download() {
        var bitmap = getViewBitmap(layContent)
        if (bitmap == null) {
            Toast.makeText(this, "图片已保存失败", Toast.LENGTH_SHORT).show()
        }
        val res = FileUtil2.saveImageToGallery(this,bitmap,"${System.currentTimeMillis()}.jpg")
        if (res) {
            Toast.makeText(this, "图片已保存至相册", Toast.LENGTH_SHORT).show()
        }else{
            Toast.makeText(this, "图片已保存失败", Toast.LENGTH_SHORT).show()
        }
    }


    var bitmap:Bitmap? = null

    private fun getViewBitmap(view: View): Bitmap? {
        if (bitmap != null) {
            return bitmap
        }

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.RGB_565)
        bitmap?.density = resources.displayMetrics.densityDpi
        val canvas = Canvas(bitmap!!)
        view.draw(canvas)
        return bitmap
    }


    companion object{

        fun startActivity(context: Context,bean: NovelDetailBean) {
            val intent = Intent(context,StoryPosterActivity::class.java)
            intent.putExtra(Constant.DATA,bean)
            context.startActivity(intent)
        }
    }
}